//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Membership;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
namespace DotNetNuke.Modules.Admin.Portals
{
	partial class Signup : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			if (IsHostMenu)
			{
				this.ModuleConfiguration.ModuleTitle = Services.Localization.Localization.GetString("AddPortal", this.LocalResourceFile);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
			optType.SelectedIndexChanged += new EventHandler(optType_SelectedIndexChanged);
			btnCustomizeHomeDir.Click += new EventHandler(btnCustomizeHomeDir_Click);
			cboTemplate.SelectedIndexChanged += new EventHandler(cboTemplate_SelectedIndexChanged);

			try
			{
				string strFolder;
				string strMessage;
				if ((!IsHostMenu || UserInfo.IsSuperUser == false) && !Host.DemoSignup)
				{
					Response.Redirect(Common.Globals.NavigateURL("Access Denied"), true);
				}
				valEmail2.ValidationExpression = Common.Globals.glbEmailRegEx;
				if (!Page.IsPostBack)
				{
					strFolder = Common.Globals.HostMapPath;
					if (System.IO.Directory.Exists(strFolder))
					{
						string[] fileEntries = System.IO.Directory.GetFiles(strFolder, "*.template");
						foreach (string strFileName in fileEntries)
						{
							if (Path.GetFileNameWithoutExtension(strFileName) != "admin")
							{
								cboTemplate.Items.Add(Path.GetFileNameWithoutExtension(strFileName));
							}
						}
						if (cboTemplate.Items.Count == 0)
						{
							lblMessage.Text = Localization.GetString("PortalMissing", this.LocalResourceFile);
							cmdUpdate.Enabled = false;
						}
						cboTemplate.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "-1"));
						cboTemplate.SelectedIndex = 0;
					}
					if (UserInfo.IsSuperUser == true)
					{
						rowType.Visible = true;
						optType.SelectedValue = "P";
					}
					else
					{
						optType.SelectedValue = "C";
						txtPortalName.Text = Common.Globals.GetDomainName(Request) + "/";
						rowType.Visible = false;
						strMessage = string.Format(Localization.GetString("DemoMessage", this.LocalResourceFile), Host.DemoPeriod != Null.NullInteger ? " for " + Host.DemoPeriod + " days" : "", Common.Globals.GetDomainName(Request));
						lblInstructions.Text = strMessage;
						btnCustomizeHomeDir.Visible = false;
					}
					txtHomeDirectory.Text = "Portals/[PortalID]";
					txtHomeDirectory.Enabled = false;
					if (MembershipProviderConfig.RequiresQuestionAndAnswer)
					{
						trQuestion.Visible = true;
						trAnswer.Visible = true;
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			txtPassword.Attributes["value"] = txtPassword.Text;
			txtConfirm.Attributes["value"] = txtConfirm.Text;
		}
		private void cmdCancel_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (IsHostMenu)
				{
					Response.Redirect(Common.Globals.NavigateURL(), true);
				}
				else
				{
					Response.Redirect(Common.Globals.GetPortalDomainName(PortalAlias.HTTPAlias, Request, true), true);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(System.Object sender, System.EventArgs e)
		{
			if (Page.IsValid)
			{
				try
				{
					bool blnChild;
					string strMessage = string.Empty;
					string strPortalAlias;
					int intPortalId;
					string strServerPath;
					string strChildPath = string.Empty;
					PortalController objPortalController = new PortalController();
					ArrayList messages = new ArrayList();
					string schemaFilename = Server.MapPath(string.Concat(this.AppRelativeTemplateSourceDirectory, "portal.template.xsd"));
					string xmlFilename = Common.Globals.HostMapPath + cboTemplate.SelectedItem.Text + ".template";
					PortalTemplateValidator xval = new PortalTemplateValidator();
					if (!xval.Validate(xmlFilename, schemaFilename))
					{
						strMessage = Localization.GetString("InvalidTemplate", this.LocalResourceFile);
						lblMessage.Text = string.Format(strMessage, cboTemplate.SelectedItem.Text + ".template");
						messages.AddRange(xval.Errors);
						lstResults.Visible = true;
						lstResults.DataSource = messages;
						lstResults.DataBind();
						return;
					}
					txtPortalName.Text = txtPortalName.Text.ToLowerInvariant();
					txtPortalName.Text = txtPortalName.Text.Replace("http://", "");
					if (PortalSettings.ActiveTab.ParentId != PortalSettings.SuperTabId)
					{
						blnChild = true;
						strPortalAlias = txtPortalName.Text;
					}
					else
					{
						blnChild = (optType.SelectedValue == "C");
						if (blnChild)
						{
							strPortalAlias = txtPortalName.Text.Substring(txtPortalName.Text.LastIndexOf("/") + 1);
						}
						else
						{
							strPortalAlias = txtPortalName.Text;
						}
					}
                    if(!PortalAliasController.ValidateAlias(strPortalAlias, blnChild))
                    {
                        strMessage += "<br>" + Localization.GetString("InvalidName", this.LocalResourceFile);
                    }
				    if (txtPassword.Text != txtConfirm.Text)
					{
						strMessage += "<br>" + Localization.GetString("InvalidPassword", this.LocalResourceFile);
					}
					strServerPath = Common.Globals.GetAbsoluteServerPath(Request);
					if (String.IsNullOrEmpty(strMessage))
					{
						if (blnChild)
						{
							strChildPath = strServerPath + strPortalAlias;
							if (System.IO.Directory.Exists(strChildPath))
							{
								strMessage = Localization.GetString("ChildExists", this.LocalResourceFile);
							}
							else
							{
								if (PortalSettings.ActiveTab.ParentId != PortalSettings.SuperTabId)
								{
									strPortalAlias = Common.Globals.GetDomainName(Request, true) + "/" + strPortalAlias;
								}
								else
								{
									strPortalAlias = txtPortalName.Text;
								}
							}
						}
					}
					string HomeDir;
					if (txtHomeDirectory.Text != "Portals/[PortalID]")
					{
						HomeDir = txtHomeDirectory.Text;
					}
					else
					{
						HomeDir = "";
					}
					if (!string.IsNullOrEmpty(HomeDir))
					{
						Services.FileSystem.FolderController objFolderController = new Services.FileSystem.FolderController();
						if (string.IsNullOrEmpty(objFolderController.GetMappedDirectory(Common.Globals.ApplicationPath + "/" + HomeDir + "/")))
						{
							strMessage = Localization.GetString("InvalidHomeFolder", this.LocalResourceFile);
						}
						if (HomeDir.Contains("admin") || HomeDir.Contains("DesktopModules") || HomeDir.ToLowerInvariant() == "portals/")
						{
							strMessage = Localization.GetString("InvalidHomeFolder", this.LocalResourceFile);
						}
					}
					if (!string.IsNullOrEmpty(strPortalAlias))
					{
						PortalAliasInfo PortalAlias = PortalAliasController.GetPortalAliasLookup(strPortalAlias.ToLower());
						if (PortalAlias != null)
						{
							strMessage = Localization.GetString("DuplicatePortalAlias", this.LocalResourceFile);
						}
					}
					if (String.IsNullOrEmpty(strMessage))
					{
						string strTemplateFile = cboTemplate.SelectedItem.Text + ".template";
						UserInfo objAdminUser = new UserInfo();
						try
						{
							objAdminUser.FirstName = txtFirstName.Text;
							objAdminUser.LastName = txtLastName.Text;
							objAdminUser.Username = txtUsername.Text;
							objAdminUser.DisplayName = txtFirstName.Text + " " + txtLastName.Text;
							objAdminUser.Email = txtEmail.Text;
							objAdminUser.IsSuperUser = false;
							objAdminUser.Membership.Approved = true;
							objAdminUser.Membership.Password = txtPassword.Text;
							objAdminUser.Membership.PasswordQuestion = txtQuestion.Text;
							objAdminUser.Membership.PasswordAnswer = txtAnswer.Text;
							objAdminUser.Profile.FirstName = txtFirstName.Text;
							objAdminUser.Profile.LastName = txtLastName.Text;
							intPortalId = objPortalController.CreatePortal(txtTitle.Text, objAdminUser, txtDescription.Text, txtKeyWords.Text, Common.Globals.HostMapPath, strTemplateFile, HomeDir, strPortalAlias, strServerPath, strChildPath,
							blnChild);
						}
						catch (Exception ex)
						{
							intPortalId = Null.NullInteger;
							strMessage = ex.Message;
						}
						if (intPortalId != -1)
						{
							PortalInfo objPortal = objPortalController.GetPortal(intPortalId);
							PortalSettings newSettings = new PortalSettings();
							newSettings.PortalAlias = new PortalAliasInfo();
							newSettings.PortalAlias.HTTPAlias = strPortalAlias;
							newSettings.PortalId = intPortalId;
							newSettings.DefaultLanguage = objPortal.DefaultLanguage;
							string webUrl = Common.Globals.AddHTTP(strPortalAlias);
							try
							{
								if (PortalSettings.ActiveTab.ParentId != PortalSettings.SuperTabId)
								{
									strMessage = Mail.SendMail(PortalSettings.Email, txtEmail.Text, PortalSettings.Email + ";" + Host.HostEmail, Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", objAdminUser), Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", objAdminUser), "", "", "", "", "",
									"");
								}
								else
								{
									strMessage = Mail.SendMail(Host.HostEmail, txtEmail.Text, Host.HostEmail, Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", objAdminUser), Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", objAdminUser), "", "", "", "", "",
									"");
								}
							}
							catch (Exception ex)
							{
								strMessage = string.Format(Localization.GetString("UnknownSendMail.Error", this.LocalResourceFile), webUrl);
							}
							Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
							objEventLog.AddLog(objPortalController.GetPortal(intPortalId), PortalSettings, UserId, "", Services.Log.EventLog.EventLogController.EventLogType.PORTAL_CREATED);
							if (strMessage == Null.NullString)
							{
								Response.Redirect(webUrl, true);
							}
							else
							{
								strMessage = string.Format(Localization.GetString("SendMail.Error", this.LocalResourceFile), strMessage, webUrl);
							}
						}
					}
					lblMessage.Text = "<br>" + strMessage + "<br><br>";
				}
				catch (Exception exc)
				{
					Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
				}
			}
		}
		private void optType_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			try
			{
				if (optType.SelectedValue == "C")
				{
					txtPortalName.Text = Common.Globals.GetDomainName(Request) + "/";
				}
				else
				{
					txtPortalName.Text = "";
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void btnCustomizeHomeDir_Click(System.Object sender, System.EventArgs e)
		{
			try
			{
				if (txtHomeDirectory.Enabled)
				{
					btnCustomizeHomeDir.Text = Services.Localization.Localization.GetString("Customize", LocalResourceFile);
					txtHomeDirectory.Text = "Portals/[PortalID]";
					txtHomeDirectory.Enabled = false;
				}
				else
				{
					btnCustomizeHomeDir.Text = Services.Localization.Localization.GetString("AutoGenerate", LocalResourceFile);
					txtHomeDirectory.Text = "";
					txtHomeDirectory.Enabled = true;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cboTemplate_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			try
			{
				string filename;
				if (cboTemplate.SelectedIndex > 0)
				{
					filename = Common.Globals.HostMapPath + cboTemplate.SelectedItem.Text + ".template";
					XmlDocument xmldoc = new XmlDocument();
					XmlNode node;
					xmldoc.Load(filename);
					node = xmldoc.SelectSingleNode("//portal/description");
					if (node != null && !String.IsNullOrEmpty(node.InnerXml))
					{
						lblTemplateDescription.Visible = true;
						lblTemplateDescription.Text = Server.HtmlDecode(node.InnerXml);
					}
					else
					{
						lblTemplateDescription.Visible = false;
					}
				}
				else
				{
					lblTemplateDescription.Visible = false;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
	}
}
